package com.seari.client;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.seari.bean.DaduhuiBean;
import com.seari.bean.DaduhuiDataBean;
import com.seari.bean.ResultTrain;
import com.seari.bean.SnapshotBean;
import com.seari.client.kafka.KafkaReceiver;
import com.seari.controller.ATSWebsocketController;
import com.seari.mapper.SnapshotMapper;
import com.seari.pojo.ATSMessageBean;
import com.seari.service.AppCacheService;
import com.seari.service.SnapshotService;
import com.seari.service.TrainServiceImpl;

//数据对象快照功能，测试，待完善
@Component("SnapshotClient")
public class SnapshotClient extends BaseClient{
	protected static Logger logger = LoggerFactory.getLogger(SnapshotClient.class);
	private static final long MAX_TIME_GAP = 10 * 60 * 1000; //最大信息有效间隔：10分钟
	
	@Autowired
	private AppCacheService appCacheService;
	
	@Autowired
	private SnapshotService snapshotService;

	@Override
	public void process() throws Exception {
//		List<SnapshotBean> snapshotBeans = snapshotService.getSnapshotByTime();
//		for (SnapshotBean snapshotBean : snapshotBeans)
//		{
//			ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(snapshotBean.getObj()));
//			HashMap<String, Object> sscacheMap = (HashMap<String, Object>) ois.readObject();
//			System.out.println(sscacheMap);
//		}
		insertCacheToDatabase();
	}
	
	private void insertCacheToDatabase() throws IOException
	{
		HashMap<String, Object> cacheMap = appCacheService.getCacheMap();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		try
		{
			oos.writeObject(cacheMap);
			byte[] bytes = bos.toByteArray();
			snapshotService.insertObject(bytes);
		} catch (Exception e)
		{
			e.printStackTrace();
		}finally {
			bos.flush();
			bos.close();
			oos.flush();
			oos.close();
		}
	}

}
